    //
//  Setup.m
//  iStock Global
//
//  Created by Andy on 2010/11/12.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "Setup.h"
#import "TSO_Setup_TableViewCell.h"
//#import "InAppPurchaseManager.h"

@implementation Setup
 

#pragma mark -
#pragma mark 判斷是否為iPad 或是iPhone函數
 
#pragma mark -
#pragma mark 自設初始化
-(void)get_navcontroller:(navcontroller *)nd{
	navdelegete=nd;
}
-(void)initTitle:(NSString *)bartitle{
	self.title=bartitle;
	
}
-(void)initImage:(UIImage*)image{
	self.tabBarItem.image= image ;
}



// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
} 

#pragma mark -
#pragma mark 開始

- (void)loadView {
	
	
	UIView *mainview;
	mainview=[[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
	self.view=mainview;
    [mainview release];
    
	self.view.backgroundColor=[UIColor lightTextColor];	
	 
	
	 myTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 800.0f)  style:UITableViewStyleGrouped];
	 
	StockInformation_0 = [[NSArray arrayWithObjects:
						   NSLocalizedString(@"Adjusted Dividends,splits", @"使用還權資料"),
						   NSLocalizedString(@"BackUp Service Data", @"使用備援伺服器資料"),
						   NSLocalizedString(@"Start Date", @"資料起始日"),
                           NSLocalizedString(@"Price Up Color ", @"上漲顏色"),
                           NSLocalizedString(@"Price Down Color ", @"下跌顏色"),		
                           // NSLocalizedString(@"Upgrade to Pro USD:9.9/year", @"升級至要專業版 美金4.9/年"),
						   nil] retain];	
	 
	
	myTable.dataSource = self;	//連結資料 UITableViewDataSource
	myTable.delegate=self; //連結動作 UITableViewDelegate	
	[self.view addSubview:myTable];
	 	
	
	//設定日期選擇扭
	
	
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
       datepick=[[UIDatePicker alloc] initWithFrame:CGRectMake(0.0f, 360.0f, 320.0f, 216.0f)]; 
    }    
	else{
       datepick=[[UIDatePicker alloc] initWithFrame:CGRectMake(0.0f, 160.0f, 320.0f, 216.0f)];
    }    
    
    
    datepick.datePickerMode=UIDatePickerModeDate;
	[datepick addTarget:self action:@selector(changeDate:) forControlEvents:UIControlEventValueChanged];
	
	
	//取出設定檔資料
	 
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];	 
    datepick.date=[prefs objectForKey:@"startUseDate"] ;	
	[self.view addSubview:datepick];
	datepick.hidden=YES;	
	
}


#pragma mark -
#pragma mark TableDelgete

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	switch (section) {
		case 0:
			return   [StockInformation_0 count];
			break;
            
	} 
	return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	static NSString *CellIdentifier = @"TableCellAddStockWatchList";
    
    TSO_Setup_TableViewCell *cell =(TSO_Setup_TableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	if (cell == nil) {
        cell = [[[TSO_Setup_TableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
	cell.textLabel.text = [StockInformation_0 objectAtIndex:indexPath.row];	
	cell.textLabel.font=[UIFont boldSystemFontOfSize:14];
	
	switch (indexPath.section) {
		case 0:{
			if (indexPath.row==0) {
				
				//是否開啓最佳化 @"Search By Name" tag=100 
				//讓表格的列不會被使用者點選時出現藍色的狀態
				cell.selectionStyle=UITableViewCellSelectionStyleNone;
				
				UISwitch *onoff;
				onoff = [[UISwitch alloc] initWithFrame: CGRectZero];
				onoff.tag=100; //isActiveOptimize
				[onoff addTarget: self action: @selector(switchChange:) forControlEvents: UIControlEventValueChanged];
				
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];				
				if ([(NSString *)[prefs  objectForKey:@"isUseAfterStockSplit" ] isEqualToString:@"Y"]) {
				    onoff.on=YES;					
				}
				else {
                    onoff.on=NO;
				}
                
				
				[self.view addSubview: onoff];
				cell.accessoryView=onoff;
				[onoff release];				 				
			}
			if (indexPath.row==1) {
				
				//是否開啓最佳化 @"Search By Name" tag=100 
				//讓表格的列不會被使用者點選時出現藍色的狀態
				cell.selectionStyle=UITableViewCellSelectionStyleNone;
				
				UISwitch *onoff;
				onoff = [[UISwitch alloc] initWithFrame: CGRectZero];
				onoff.tag=200; //isActiveOptimize
				[onoff addTarget: self action: @selector(switchChange:) forControlEvents: UIControlEventValueChanged];
				
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];				
				if ([(NSString *)[prefs  objectForKey:@"isUseBackUPdatabase" ] isEqualToString:@"Y"]) {
				    onoff.on=YES;					
				}
				else {
					onoff.on=NO;
				}
				
				
				[self.view addSubview: onoff];
				cell.accessoryView=onoff;
				[onoff release];				 				
			}
			if (indexPath.row==2) {
                
				
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];				
				
				NSDateFormatter* df = [[NSDateFormatter alloc]init];
				[df setDateFormat:@"yyyy/MM/dd"];
				NSString *result = [df stringFromDate:[prefs objectForKey:@"startUseDate"]];	
				cell.name.text=result;		
				[df release];
				
				
				
			}
            if (indexPath.row==3) {
				
				//是否開啓最佳化 @"Search By Name" tag=100 
				//讓表格的列不會被使用者點選時出現藍色的狀態
				cell.selectionStyle=UITableViewCellSelectionStyleNone;
				
                NSArray *textoptionarray=[NSArray arrayWithObjects: NSLocalizedString(@"Green",@"綠色"), NSLocalizedString(@"Red",@"紅色"),nil];
                
                segmetnctl_upColor=[[UISegmentedControl alloc] initWithItems:textoptionarray];
                [ segmetnctl_upColor addTarget:self action:@selector(segmentChanged_upColor) forControlEvents:UIControlEventValueChanged];
                segmetnctl_upColor.frame=CGRectMake(0, 0, 120, 30);	
                
                
                NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];                 
                
                if ([[prefs objectForKey:@"upColor"] isEqualToString:@"greenColor" ] ) {
                    segmetnctl_upColor.selectedSegmentIndex=0;	
                    
                    
                } 
                else if ([[prefs objectForKey:@"upColor"] isEqualToString:@"redColor" ] ) {
                    segmetnctl_upColor.selectedSegmentIndex=1;	
                }                      
                
                
                
                [self.view addSubview:  segmetnctl_upColor];
				cell.accessoryView= segmetnctl_upColor;
				[ segmetnctl_upColor release];				 				
			}
            if (indexPath.row==4) {
				
				//是否開啓最佳化 @"Search By Name" tag=100 
				//讓表格的列不會被使用者點選時出現藍色的狀態
				cell.selectionStyle=UITableViewCellSelectionStyleNone;
				
                NSArray *textoptionarray=[NSArray arrayWithObjects: NSLocalizedString(@"Green",@"綠色"), NSLocalizedString(@"Red",@"紅色"),nil];  
                segmetnctl_downColor=[[UISegmentedControl alloc] initWithItems:textoptionarray];
                [segmetnctl_downColor addTarget:self action:@selector(segmentChanged_downColor) forControlEvents:UIControlEventValueChanged];
                segmetnctl_downColor.frame=CGRectMake(0, 0, 120, 30);	
                
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];                 
                
                if ([[prefs objectForKey:@"downColor"] isEqualToString:@"greenColor" ] ) {
                    segmetnctl_downColor.selectedSegmentIndex=0;	
                } 
                else if ([[prefs objectForKey:@"downColor"] isEqualToString:@"redColor" ] ) {
                    segmetnctl_downColor.selectedSegmentIndex=1;	
                }                               
                
				[self.view addSubview: segmetnctl_downColor];
				cell.accessoryView=segmetnctl_downColor;
				[segmetnctl_downColor release];	
                
			}            
            
            
            
			break;
		}
            
			
	}
	if ([cell.textLabel.text isEqualToString:@"資料起始日"]  ){
		
		cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
	}	
	else {
		cell.accessoryType=UITableViewCellAccessoryNone;		
	}		
	
	return cell;
}
  
#pragma mark -
#pragma mark TableSelected
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
    
	if (indexPath.section==0 && indexPath.row==2) {
		//顯示日起顯示器 
		datepick.hidden=NO;
	}
	else {
		datepick.hidden=YES;
	}
    
	if (indexPath.section==0 && indexPath.row==3) {
		NSLog(@"升級至要專業版");
		//InAppPurchaseManager *IAP;
		//IAP=[[InAppPurchaseManager alloc] init]; 
		//很重要 如果沒有這一段 則 app stor 不會回應 delegete
		//[[SKPaymentQueue defaultQueue] addTransactionObserver:IAP];
		//[IAP requestProUpgradeProductData];
		
		
	}
	
}



- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
	NSString *title = nil;
	switch (section) {
		case 0:{
            NSString *DisplayName;
            DisplayName=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"]; 
            
            //版本字串
            NSString *ver;
            ver=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
            
            
            //標記:判斷是否為iPad 或是iPhone 範例 (應用)
            if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
            {
                 title = [NSString stringWithFormat: @"%@ For iPad   \n Version %@ \n © xxTradexx Stock Tradeing System Inc. \n www.xtradexx.com ",DisplayName   ,ver] ;                
                
            }
            else
            {
                 title = [NSString stringWithFormat: @"%@ For iPhone   \n Version %@ \n © xxTradexx Stock Tradeing System Inc. \n www.xtradexx.com ",DisplayName   ,ver] ;                
                
            }
            
            
            
            break;
		}
            
		default:
			break;
	}
	return title;	
	
	
}




- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 3;
}

-(void)segmentChanged_upColor{
   NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];    
    if (segmetnctl_upColor.selectedSegmentIndex==0) {
        NSLog(@"up_Green");
        [prefs setObject:@"greenColor"  forKey:@"upColor"];
        [prefs synchronize];	 		
        
    } 
    else  if (segmetnctl_upColor.selectedSegmentIndex==1) {
        NSLog(@"up_Red");    
        [prefs setObject:@"redColor"  forKey:@"upColor"];
        [prefs synchronize];        
        
    }    
    
} 
-(void)segmentChanged_downColor{
   NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];    
    
    if (segmetnctl_downColor.selectedSegmentIndex==0) {
        NSLog(@"down_Green");
        
        [prefs setObject:@"greenColor"  forKey:@"downColor"];
        [prefs synchronize];        
    } 
    else  if (segmetnctl_downColor.selectedSegmentIndex==1) {
        NSLog(@"down_Red");        
        [prefs setObject:@"redColor"  forKey:@"downColor"];
        [prefs synchronize];         
        
        
    }    
}



- (void)dealloc {	
	
	[myTable release];
	[StockInformation_0 release];
	 
	[super dealloc];
}
#pragma mark -
#pragma mark  按鈕轉換
-(void)switchChange:(id) sender{
	
	UISwitch *onoff = (UISwitch *) sender;	
	
	
	switch (onoff.tag) {
		case 100:{
			//搜尋是否要使用名稱
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
					 
			if (onoff.on==YES) {
				[prefs setObject:@"Y" forKey:@"isUseAfterStockSplit"];
				[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 					
				
			}
			else {
				[prefs setObject:@"N" forKey:@"isUseAfterStockSplit"];
				[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 					 
			}
			
			 
			
			
			
			break;
		}
			
		case 200:{
			//搜尋是否要使用名稱
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			
			if (onoff.on==YES) {
				[prefs setObject:@"Y" forKey:@"isUseBackUPdatabase"];
				[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 					
				
			}
			else {
				[prefs setObject:@"N" forKey:@"isUseBackUPdatabase"];
				[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 					 
			}
			
			
			
			
			
			break;
		}
			
		default:
			break;
	}
	
	
	
	
	
}



#pragma mark -
#pragma mark  日期挑選器改變值 日期一但改變就刪除所有之前下載的股價資料
-(void) changeDate:(UIDatePicker *) picker{
	//設定全部時間
 	
	NSTimeInterval  l;
	l=[[picker date] timeIntervalSinceDate:[NSDate date]]/86400;
	float year;
	year=l/365;	
	if (year<=-1.0) {
		//NSLog(@"cccccc=%f",year);
		NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
		[prefs setObject:[picker date] forKey:@"startUseDate"];
		[prefs synchronize];	
		
		[myTable reloadData];
		
        //NSLog(@"日期一但改變就刪除所有之前下載的股價資料 ");
		//日期一但改變就刪除所有之前下載的股價資料 ********
		[self deletallStockData];
		
		
		
	}
	else {
		UIAlertView *ui;
		ui=[[UIAlertView alloc] initWithTitle:@"選擇起始日" message:@"請選擇離目前時間一年以前的日期" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
		[ui show];
	}

	
		
}

-(void)deletallStockData{
	//delete document 下面所有.plist檔案 就是股價與計算資料
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
	NSString *docPath = [paths objectAtIndex:0];	
	 
    
	NSFileManager  *fileManager = [NSFileManager defaultManager];
	NSDirectoryEnumerator *dirEnumerator = [fileManager enumeratorAtPath:docPath ]; 
	NSString *currPath; 
	 
	 
   
    while (currPath = [dirEnumerator nextObject]) 
	{ 
		NSLog(@"b");
        NSDictionary *attributes = [dirEnumerator fileAttributes];
		NSString *fType  = [attributes objectForKey:NSFileType];
		
		if([fType isEqualToString:NSFileTypeDirectory] == YES){
			 NSLog(@"Found a directory: %@", currPath);
		}
		else{
			//NSNumber *fSize  = [attributes objectForKey:NSFileSize];
		    NSArray *copm=[currPath componentsSeparatedByString:@"."];
			//刪除美國股票
			if ([copm count]==2) {
				//NSLog(@"刪除美國股票");
                if ([[copm objectAtIndex:1] isEqualToString:@"plist"]) {
					// NSLog(@"Found a file: %@,  size: %qi  %@ \n", currPath, [fSize unsignedLongLongValue],fType);					
					//NSString *delpath;
					//delpath=[docPath stringByAppendingPathComponent:currPath];
					//success=[fileManager removeItemAtPath:delpath error:&error];
					//[delpath release];
				}
			}
			//刪除美國以外股票資料
			if ([copm count]==3) {
				//NSLog(@"刪除美國以外股票資料");
                if ([[copm objectAtIndex:2] isEqualToString:@"plist"]) {
					//NSLog(@"Found a file: %@,  size: %qi  %@ \n", currPath, [fSize unsignedLongLongValue],fType);					
					//NSString *delpath;
					//delpath=[docPath stringByAppendingPathComponent:currPath];
					//success=[fileManager removeItemAtPath:delpath error:&error];
					//[delpath release];
				}
			}		
		}
	} 
	//========================================
} 

@end
